"""
AI角色扮演应用后端 - FastAPI应用定义
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from app.core.config import settings
from app.core.database import engine, Base
from app.api.v1.api import api_router
from app.core.exceptions import setup_exception_handlers
from app.core.rate_limit import limiter, _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from starlette.middleware.gzip import GZipMiddleware


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时创建数据库表
    Base.metadata.create_all(bind=engine)
    yield
    # 关闭时清理资源


def create_app() -> FastAPI:
    """创建FastAPI应用实例"""
    app = FastAPI(
        title=settings.APP_NAME,
        version=settings.APP_VERSION,
        description="AI角色扮演应用后端API",
        lifespan=lifespan
    )

    # 添加CORS中间件
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],  # 生产环境应该设置具体的域名
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # 启用GZip压缩，减小响应体体积
    app.add_middleware(GZipMiddleware, minimum_size=500)

    # 设置异常处理器
    setup_exception_handlers(app)

    # 设置限流异常处理器
    app.state.limiter = limiter
    app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

    # 包含API路由
    app.include_router(api_router, prefix="/api")

    # 添加基础路由
    @app.get("/")
    async def root():
        return {"message": "AI角色扮演应用后端API", "version": settings.APP_VERSION}

    @app.get("/health")
    async def health_check():
        return {"status": "healthy"}

    return app


# 创建应用实例
app = create_app()
